<template>
  <h1>测试vee-validate</h1>
  <Form ref="target" :validation-schema="schema" v-slot="{ errors }">
    <Field v-model="formData.mobile" name="mobile" type="text" placeholder="请输入手机号" />
    <Field v-model="formData.password" name="password" type="password" placeholder="请输入密码" />
    <div class="error" v-if="errors.mobile">{{ errors.mobile }}</div>
    <div class="error" v-if="errors.password">{{ errors.password }}</div>
    <button @click="submit">登录</button>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { reactive, ref } from 'vue'
export default {
  components: { Form, Field },
  setup() {
    const target = ref(null)
    const formData = reactive({ mobile: '13600001567', password: '123456' })
    // 表单验证
    const schema = {
      mobile(value) {
        if (!value) return '请输入手机号'
        if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式错误'
        return true
      },
      password(value) {
        if (!value) return '请输入密码'
        if (!/\d{6}$/.test(value)) return '密码格式错误'
        return true
      }
    }
    const submit = () => {
      target.value.validate().then(res => {
        console.log('表单校验结果', res)
      })
    }

    return { formData, schema, submit, target }
  }
}
</script>

<style></style>
